<?php

namespace Pay;

/**
 * Class Pay
 * @package app\api\controller
 * 原点 2020年5月30日09:10:42 支付宝APP支付
 */
class Alipay
{
    /**
     * @var string 支付宝应用ID
     */
    private $APP_ID;

    /**
     * @var string  支付宝私钥
     */
    private $PrivateKey;

    /**
     * @var string  支付宝公钥
     */
    private $PublicKey;

    private $aop;

    public function __construct(array $config = [])
    {
        require_once 'alipayrsa2/aop/AopClient.php';
        require_once 'alipayrsa2/aop/request/AlipayTradeAppPayRequest.php';
        $this->APP_ID = $config['app_id'];
        $this->PrivateKey = $config['public_key'];
        $this->PublicKey = $config['private_key'];
        $this->aop =  new \AopClient;
    }

    /**
     * @param array $param
     * @return string
     * 原点 2019年11月5日13:59:31 支付宝支付所需参数
     */
    public function AliPay(array $param = [])
    {

        $this->aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $this->aop->appId = $this->APP_ID;
        $this->aop->rsaPrivateKey = $this->PrivateKey;
        $this->aop->format = "json";
        $this->aop->charset = "UTF-8";
        $this->aop->signType = "RSA2";
        $this->aop->alipayrsaPublicKey = $this->PublicKey;
        $request = new \AlipayTradeAppPayRequest();
        $bizcontent = "{\"body\":\"" . $param['title'] . "\","
            . "\"subject\": \"" . $param['subject'] . "\","
            . "\"out_trade_no\": \"" . $param['out_trade_no'] . "\","
            . "\"timeout_express\": \"30m\","
            . "\"total_amount\": \"" . $param['total'] . "\","
            . "\"product_code\":\"QUICK_MSECURITY_PAY\""
            . "}";
        $notify_url = $param['notify_url'];
        $request->setNotifyUrl($notify_url);
        $request->setBizContent($bizcontent);
        $response = $this->aop->sdkExecute($request);
        return $response;
    }


    /**
     * @return bool
     * 原点 2020年5月30日09:10:17 支付宝回调
     */
    public function AlipayNotify()
    {

        $this->aop->alipayrsaPublicKey = $this->PublicKey;
        $flag = $this->aop->rsaCheckV1($_POST, NULL, "RSA2");
        if ($flag == true && $_POST['trade_status'] == 'TRADE_SUCCESS') {
            return $_POST;
//            echo "success";
        } else {
            return false;
//            echo "fail";
        }
    }

}
